package com.joy.conf.mybatisPlus;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.joy.common.constant.CommonCons;
import com.joy.common.model.vo.UserInfoVO;
import lombok.extern.slf4j.Slf4j;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @ClassName: CommonFieldHandler
 * @Description: 通用字段填充
 * @Author: yjzhao
 * @Create: 2019-09-09  11:26
 **/
@Slf4j
@Component
public class CommonFieldHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        //TODO createId、updateId 自动获取当前用户
        log.info("start insert fill ....");
        this.setFieldValByName("delYn", CommonCons.FlagType.N, metaObject);
        this.setFieldValByName("createId", getUserId(), metaObject);
        this.setFieldValByName("createDts", new Date(), metaObject);
        this.setFieldValByName("updateId", getUserId(), metaObject);
        this.setFieldValByName("updateDts", new Date(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        this.setFieldValByName("updateId", getUserId(), metaObject);
        this.setFieldValByName("updateDts", new Date(), metaObject);
    }

    /**
     * @Description 获取用户详情信息
     * @param
     * @return
     * @Author yjzhao
     * @Date 2019/9/17 21:03
     **/
    private String getUserId() {
        String userId = "sys_temp";
        try {
            Subject subject = SecurityUtils.getSubject();
            if (subject == null || subject.getPrincipal() == null) {
                return userId;
            }
            String userNm = (String)subject.getPrincipal();
            if (StrUtil.isEmpty(userNm)) {
                return userId;
            }
            Cache userInfosCache = CacheManager.getInstance().getCache(CommonCons.MyCache.USERINFOS);
            Element userInfoEle = userInfosCache.get(userNm);
            if (userInfoEle == null) {
                return userId;
            }
            UserInfoVO userInfoVO = (UserInfoVO) userInfoEle.getObjectValue();
            userId = userInfoVO.getUserId();
            if (StrUtil.isEmpty(userId)) {
                return "sys_temp";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return userId;
    }
}
